package com.mdp.arc.pub.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.arc.pub.entity.Category;
import com.mdp.arc.pub.entity.CategoryQx;
import com.mdp.arc.pub.mapper.CategoryMapper;
import com.mdp.core.entity.LangTips;
import com.mdp.core.query.QueryTools;
import com.mdp.core.service.BaseService;
import com.mdp.core.utils.ObjectTools;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 父类已经支持增删改查操作,因此,即使本类什么也不写,也已经可以满足一般的增删改查操作了.<br> 
 * 组织 com.mdp  顶级模块 arc 大模块 pub 小模块 <br>
 * 实体 Category 表 arc_category 当前主键(包括多主键): id; 
 ***/
@Service("mdp.arc.pub.service.CategoryService")
@DS("arc-ds")
public class CategoryService extends BaseService<CategoryMapper,Category> {
	static Logger logger =LoggerFactory.getLogger(CategoryService.class);

	@Autowired
	CategoryQxService qxService;

	/**
	 * 自定义查询，支持多表关联
	 * @param page 分页条件
	 * @param ew 一定要，并且必须加@Param("ew")注解
	 * @param ext 如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
	 * @return
	 */
	public List<Map<String,Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String,Object> ext){
		return baseMapper.selectListMapByWhere(page,ew,ext);
	}


	/** 请在此类添加自定义函数 */

	public  int insert(Category category) {
		category.setPaths(calcPidString(category));
		int i= super.insert(category);
		return i;

	}

	public String calcPidString(Category category){
		StringBuilder sbIdPath = new StringBuilder();
		if (!StringUtils.hasText(category.getPid())||category.getPid().equals("0")||category.getId().equals(category.getPid())) {
			sbIdPath.append("0,");
			sbIdPath.append(category.getId());
		} else {
			List<Map<String, Object>> pListMap = getAllParentNode(category.getPid(), new ArrayList<>());
			List<String> lsId = new ArrayList<>();
			if (!CollectionUtils.isEmpty(pListMap)) {
				int j = pListMap.size();
				for (int i = 0; i < j; i++) {
					lsId.add((String) pListMap.get(j-i-1).get("id"));
				}

				//  JDK8 +.
				//  idPath = String.join(",", lsId);
				sbIdPath.append("0,");
				sbIdPath.append(lsId.stream().collect(Collectors.joining(",")));
				sbIdPath.append(",");
				sbIdPath.append(category.getId());
			}
		}
		return sbIdPath.toString();
	}

	/**
	 * 递归获取所有上级所有节点
	 *
	 * @param pcategoryId
	 * @param pListMap
	 * @return
	 */
	public List<Map<String, Object>> getAllParentNode(String pcategoryId, List<Map<String, Object>> pListMap) {
		if(!StringUtils.hasText(pcategoryId)||"0".equals(pcategoryId)){
			return pListMap;
		}
		Map<String, Object> map = new HashMap<>();
		map.put("id", pcategoryId);
		List<Map<String, Object>> list = this.selectListMapByWhere(QueryTools.initPage(map),QueryTools.initQueryWrapper(Category.class,map),map);
		if (!CollectionUtils.isEmpty(list)) {
			Map<String,Object> data=list.get(0);
			String pid= (String) data.get("pid");
			if(!StringUtils.hasText(pid) || pid.equals(pcategoryId)||"0".equals(pid)){
				pListMap.add(data);
				return pListMap;
			}
			pListMap.add(data);
			getAllParentNode(pid, pListMap);
		}
		return pListMap;
	}
	public   int updateByPk(Category category) {
		category.setPaths(calcPidString(category));
		int i= super.updateByPk(category);
		return i;
	}

	public   int[] batchDeleteByMyBranchId(List<Category> categorys,String branchId) {


		if(categorys==null || categorys.size()<=0) {
			return null;
		}

		int[] is= super.batchDelete(categorys);
		return is;
	}

	public   int deleteByPk(Category category) {

		int i= super.deleteByPk(category);
		return i;
	}

	@Transactional
	public void batchSave(List<Category> collect, List<Category> updates) {
		List<Category> all=new ArrayList<>();
		if(collect!=null && collect.size()>0){
			this.batchInsert(collect);
			all.addAll(collect);
		}

		if(updates!=null && updates.size()>0){
			this.batchUpdate(updates);
			all.addAll(updates);
		}
		for (Category category : all) {
			category.setPaths(this.calcPidString(category));

		}
		baseMapper.batchUpdatePaths(all);


	}

	/**
	 *
	 * @param pcate
	 * @param checkType qry,edit,del
	 * @return
	 */
	public LangTips checkQx(Category pcate,String checkType){
		User user=LoginUtils.getCurrentUserInfo();
		String[] pids=pcate.getPaths().split(",");
		CategoryQx categoryQx= qxService.getOne(QueryTools.initQueryWrapper(CategoryQx.class).in("cate_id",pids));
		String op="qry".equals(checkType)?categoryQx.getOthQuery():("edit".equals(checkType)?categoryQx.getOthEdit():categoryQx.getOthDel());
		String roleids="qry".equals(checkType)?categoryQx.getQryRoleids():("edit".equals(checkType)?categoryQx.getEditRoleids():categoryQx.getDelRoleids());;
		String deptids="qry".equals(checkType)?categoryQx.getQryDeptids():("edit".equals(checkType)?categoryQx.getEditDeptids():categoryQx.getDelDeptids());;
		String userids="qry".equals(checkType)?categoryQx.getQryUserids():("edit".equals(checkType)?categoryQx.getEditUserids():categoryQx.getDelUserids());;


		String nroleids="qry".equals(checkType)?categoryQx.getNqRoleids():("edit".equals(checkType)?categoryQx.getNeRoleids():categoryQx.getNdRoleids());;
		String ndeptids="qry".equals(checkType)?categoryQx.getNqDeptids():("edit".equals(checkType)?categoryQx.getNeDeptids():categoryQx.getNdDeptids());;
		String nuserids="qry".equals(checkType)?categoryQx.getNqUserids():("edit".equals(checkType)?categoryQx.getNeUserids():categoryQx.getNdUserids());;
		if(categoryQx!=null){
			if("1".equals(op)){
				boolean roleCheckOk=false;
				boolean useridCheckOk=false;
				boolean deptidCheckOk=false;
				if(ObjectTools.isNotEmpty(roleids)){
					if(LoginUtils.hasAnyRoles(roleids.split(","))){
						roleCheckOk=true;
					}
				}
				if(ObjectTools.isNotEmpty(userids)){
					if(Arrays.stream(userids.split(",")).filter(k->user.getUserid().equals(k)).findAny().isPresent()){
						useridCheckOk=true;
					}
				}

				if(ObjectTools.isNotEmpty(deptids)){
					if(Arrays.stream(deptids.split(",")).filter(k->user.getDeptid().equals(k)).findAny().isPresent()){
						deptidCheckOk=true;
					}
				}
				boolean allowCheckOk=roleCheckOk||useridCheckOk||deptidCheckOk;
				boolean notAllow=false;
				if(ObjectTools.isNotEmpty(nroleids)){
					if(LoginUtils.hasAnyRoles(nroleids.split(","))){
						notAllow=true;
					}
				}
				if(ObjectTools.isNotEmpty(nuserids)){
					if(Arrays.stream(nuserids.split(",")).filter(k->user.getUserid().equals(k)).findAny().isPresent()){
						notAllow=true;
					}
				}

				if(ObjectTools.isNotEmpty(ndeptids)){
					if(Arrays.stream(ndeptids.split(",")).filter(k->user.getDeptid().equals(k)).findAny().isPresent()){
						notAllow=true;
					}
				}
				//禁止条款优先级最高
				//如果是被禁止的任一条款满足条件，则全部禁止
				if( notAllow ){
					return LangTips.errMsg("no-qx-edit","无权限在分类【%s】进行新增子分类、修改等操作",pcate.getName());
				}else if(!allowCheckOk){//如果被允许的任意条款满足，则允许
					if(ObjectTools.isNotEmpty(roleids)||ObjectTools.isNotEmpty(deptids)||ObjectTools.isNotEmpty(userids)){
						return LangTips.errMsg("no-qx-query","无权限查询");
					}
				}

			} else{
				return LangTips.errMsg("no-qx-edit","无权限在分类【%s】进行新增子分类、修改等操作",pcate.getName());

			}

		}
		return LangTips.okMsg();
	}

	public void updatecategoryTypeByPid(Category category) {
	}
}

